package com.doule.farmerassistant.autoupdate;

import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.net.Uri;
import android.net.http.AndroidHttpClient;
import android.os.Environment;
import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p/>
 * TODO: Customize class - update intent actions, extra parameters and static
 * helper methods.
 */
public class DownloadIntentService extends IntentService {
    // TODO: Rename actions, choose action names that describe tasks that this
    // IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
    private static final String ACTION_FOO = "com.doule.farmerassistant.autoupdate.action.FOO";
    private static final String ACTION_BAZ = "com.doule.farmerassistant.autoupdate.action.BAZ";

    // TODO: Rename parameters
    private static final String EXTRA_PARAM1 = "com.doule.farmerassistant.autoupdate.extra.PARAM1";
    private static final String EXTRA_PARAM2 = "com.doule.farmerassistant.autoupdate.extra.PARAM2";

    private static final String TAG = "DownloadIntentService";

    private String mApkUrl;
    private File mApkFile;

    /**
     * Starts this service to perform action Foo with the given parameters. If
     * the service is already performing a task this action will be queued.
     *
     * @see IntentService
     */
    // TODO: Customize helper method
    public static void startActionFoo(Context context, String param1, String param2) {
        Intent intent = new Intent(context, DownloadIntentService.class);
        intent.setAction(ACTION_FOO);
        intent.putExtra(EXTRA_PARAM1, param1);
        intent.putExtra(EXTRA_PARAM2, param2);
        context.startService(intent);
    }

    /**
     * Starts this service to perform action Baz with the given parameters. If
     * the service is already performing a task this action will be queued.
     *
     * @see IntentService
     */
    // TODO: Customize helper method
    public static void startActionBaz(Context context, String param1, String param2) {
        Intent intent = new Intent(context, DownloadIntentService.class);
        intent.setAction(ACTION_BAZ);
        intent.putExtra(EXTRA_PARAM1, param1);
        intent.putExtra(EXTRA_PARAM2, param2);
        context.startService(intent);
    }

    public DownloadIntentService() {
        super("DownloadIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_FOO.equals(action)) {
                final String param1 = intent.getStringExtra(EXTRA_PARAM1);
                final String param2 = intent.getStringExtra(EXTRA_PARAM2);
                handleActionFoo(param1, param2);
            } else if (ACTION_BAZ.equals(action)) {
                final String param1 = intent.getStringExtra(EXTRA_PARAM1);
                final String param2 = intent.getStringExtra(EXTRA_PARAM2);
                handleActionBaz(param1, param2);
            }
        }
    }
    private void createApkFile() {
        File sdCard = Environment.getExternalStorageDirectory();
        File dir = new File (sdCard.getAbsolutePath() + "/erletek/update");
        if (dir.exists() == false) {
            dir.mkdirs();
        }

        File file = new File(dir, "FarmerAssistant.apk");
        if (file.exists()) {
            file.delete();
        }

        mApkFile = file;
    }

    /**
     * Handle action Foo in the provided background thread with the provided
     * parameters.
     */
    private void handleActionFoo(String param1, String param2) {
        mApkUrl = param1;
        createApkFile();

        if (downloadFile()) {
            startInstallApk();
        }
    }
    private boolean downloadFile() {
        HttpGet request = new HttpGet(mApkUrl);
        AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
        try {
            HttpResponse resp = client.execute(request);
            HttpEntity entity = resp.getEntity();
            if (entity == null) {
                Log.e(TAG, "http response entity is null");
                return false;
            }

            InputStream is = entity.getContent();
            long total = entity.getContentLength();

            if (total < 1) {
                Log.e(TAG, "http response content length is 0");
                return false;
            }

            byte[] b = new byte[1024];
            int l = 0;
            long d = 0;
            OutputStream out = new FileOutputStream(mApkFile);
            while ((l = is.read(b)) != -1) {
                d += l;
                out.write(b, 0, l);
            }
            out.close();

            if (total != d) {
                Log.e(TAG, "download file failed because content size not match");
                mApkFile.delete();
                return false;
            }

            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            client.close();
        }
        return false;
    }

    private void startInstallApk() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(mApkFile), "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
        startActivity(intent);
    }

    /**
     * Handle action Baz in the provided background thread with the provided
     * parameters.
     */
    private void handleActionBaz(String param1, String param2) {
        // TODO: Handle action Baz
        throw new UnsupportedOperationException("Not yet implemented");
    }
}
